import 'dart:async';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/event/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/widget/WaterFallFlow/WaterFallFlow.dart';
import 'package:thinking/widget/_.dart';
class Country extends StatefulWidget {
  @override
  _Country createState() => _Country();
}

class _Country extends State<Country>
    with AutomaticKeepAliveClientMixin<Country>,SingleTickerProviderStateMixin  {
  int countryIndex = SPreferences().getInt('country_Index') == 0
      ? 1
      : SPreferences().getInt('country_Index');

  @override
  bool get wantKeepAlive => true;
  bool isLoading = false;
  bool isThinkLoading = false;
  int timerIndex = 0;
  late CountryData countryData;
  late List<Think> thinkData = [];
  CountryPage countryPage = CountryPage();
  late EasyRefreshController _easyRefreshController;
  late AnimationController _animationController;
  Animation<Offset>? _animation;


  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _animationController =
        AnimationController(duration: Duration(seconds: 5), vsync: this)..addStatusListener((AnimationStatus status) {
          if(status == AnimationStatus.completed){
            _animationController.reverse();
          }else if(status == AnimationStatus.dismissed){
            _animationController.forward();
          }
        });

    _animation =TweenSequence([
      TweenSequenceItem(
          tween:Tween(begin: Offset(0.0,-0.5), end: Offset(0.0,-0.5)).chain(CurveTween(curve: Curves.easeIn)), weight: 30
      ),
      TweenSequenceItem(
        tween:Tween(begin: Offset(0.0,-0.5), end: Offset(0.0,-1.1)).chain(CurveTween(curve: Curves.bounceIn)), weight: 40
      ),
      TweenSequenceItem(
          tween:Tween(begin: Offset(0.0,-1.1), end: Offset(0.0,-1.1)).chain(CurveTween(curve: Curves.easeIn)), weight: 30
      )
    ]).animate(_animationController);

    _animationController.forward();

    Config.eventBus.on<ChangeCountryEvent>().listen((event) {
      if (event.update) {
        countryIndex = event.focusCountry;
        countryPage = CountryPage();
        isLoading = false;
        thinkData = [];
        setState(() {

        });
        getCountryData();
      }
    });

    getCountryData();
  }


  Future<void> getCountryData() async {
    countryData = await CountryService.getAllTime(params: {
      "country_Id": countryIndex,
    });
    timerIndex = countryData.timerList![0].timeId!;
    await getThinkData();
  }

  Future<void> getThinkData() async {

   var resultData = await CountryService.getAllThink(params: {
      "time_Id": timerIndex,
      "country_Id": countryIndex,
      "think_Page": countryPage.thinkPage,
      "think_Count": countryPage.thinkCount
    });
   if(countryPage.canThink)thinkData =(thinkData.length !=0?[...thinkData,...resultData
       .thinkData!]:resultData
       .thinkData)!;
   BotToast.showText(text: resultData.thinkData!.length == 0 || !countryPage.canThink?'没有更多think了哦~':'更新了${resultData.thinkData!.length}条think~');
   if(resultData.thinkData!.length<countryPage.thinkCount) {
     countryPage.setCanThink =false;
   }
   isLoading = true;
   isThinkLoading = false;
    setState(() {});
  }

  PageView pageView() {
    return PageView(
      children: countryData.timerList!
          .map((e) => GestureDetector(
                onTap: () {
                  timerIndex = e.timeId!;
                  thinkData = [];
                  this.isThinkLoading = true;
                  setState(() {
                  });
                  countryPage.setThinkPage =0;
                  countryPage.setCanThink = true;
                  getThinkData();
                },
                child: Stack(
                  children: [
                    Panel(
                      top: 0,
                      bottom: 0,
                      right: 15,
                      left: 15,
                      child: Container(
                        decoration: BoxDecoration(
                            color: ColorConfig.WhiteBackColor,
                            image: DecorationImage(
                                image: NetworkImage(
                                  e.timeImage!,
                                ),
                                fit: BoxFit.cover,
                            ),
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            border: timerIndex == e.timeId
                                ? Border.all(
                                    color: ColorConfig.ThemeColor, width: 2)
                                : null),
                        width:
                            Screen.width(Config.context) - Screen.setWidth(30),
                        height: Screen.setHeight(200),
                        child: GlassWidget(
                            width: double.infinity,
                            height: double.infinity,
                            borderRadius: 10,
                            blur: 0,
                            color: Color(0XFFFFFFFF),
                            linearGradientBeginOpacity: 0.5,
                            linearGradientEndOpacity: 0.1,
                            borderGradientEndOpacity: 0,
                            borderGradientBeginOpacity: 0,
                            child: Container()),
                      ),
                    ),
                     Positioned(
                        top: Screen.setHeight(8),
                        left: Screen.setWidth(25),
                        child: ClipOval(
                          child: GestureDetector(
                            onTap: (){
                              Modular.to.pushNamed('/countryList/$countryIndex');
                            },
                            child: Container(
                              height: Screen.setWidth(53),
                              width: Screen.setWidth(53),
                              constraints: BoxConstraints(
                                maxHeight: Screen.setWidth(53)
                              ),
                              decoration:
                              BoxDecoration(
                                  color: ColorConfig.ThemeColor,
                                  borderRadius: BorderRadius.all(Radius.circular(25)),
                                  border: Border.all(width:1,color: ColorConfig.WhiteBackColor)
                              ),

                              child:SlideTransition(
                                position: _animation!,
                                child:   Stack(
                                  clipBehavior: Clip.none, children: [
                                  Positioned(
                                    top: Screen.setHeight(23),
                                    child: Container(
                                      height: Screen.setWidth(53),
                                      width: Screen.setWidth(53),
                                      child: Center(
                                        child: Text(
                                          countryData.name!,
                                          style: TextStyle(
                                              color: ColorConfig.WhiteBackColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                    top: Screen.setHeight(56),
                                    child: Container(
                                      height: Screen.setWidth(53),
                                      width: Screen.setWidth(53),
                                      child: Center(
                                        child: Text(
                                          e.timeTitle!,
                                          style: TextStyle(
                                              color: ColorConfig.WhiteBackColor,
                                              fontSize: 12,
                                              fontWeight: FontWeight.w600),
                                        ),
                                      ),
                                    ),
                                  ),
                                  ],
                                ),
                              )

                             ,
                            ),
                          )
                        ),
                      ),
                    Positioned(
                      top: Screen.setHeight(65),
                      left: Screen.setWidth(25),
                      child: Container(
                        child: Text(
                          '起始于 ' + e.timeTiming!,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: ColorConfig.WhiteBackColor,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: Screen.setHeight(95),
                      left: Screen.setWidth(25),
                      child: Container(
                        constraints: BoxConstraints(
                            maxWidth: Screen.width(Config.context) -
                                Screen.setWidth(50)),
                        child: Text(
                          e.timeContent!,
                          overflow: TextOverflow.clip,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: ColorConfig.WhiteBackColor,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ))
          .toList(),
    );
  }

  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onRefresh: () async {
        if(!this.isLoading) return;
        countryPage.setThinkPage =0;
        countryPage.setCanThink = true;
        thinkData = [];
        await getThinkData();
        _easyRefreshController.finishRefresh(success: true);
      },
      onLoad: () async {
        if(!this.isLoading) return;
        if(countryPage.canThink){
          countryPage.setThinkPage = countryPage.thinkPage + 1;
        }
        await getThinkData();
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _easyRefreshController.dispose();
    super.dispose();


  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return this.isLoading
        ? Empty(
            isShow: countryData.timerList!.length == 0 ,
            child: easyRefresh(
                  CustomScrollView(shrinkWrap: true, slivers: <Widget>[
                    SliverPersistentHeader(
                        pinned: false,
                        delegate: StickyTabBarDelegate(
                            child: Panel(
                              bottom: 0,
                              left: 0,
                              top: Screen.setHeight(10),
                              right: 0,
                              child: pageView(),
                            ),
                            maxHeight: 210)),
                    SliverList(
                      delegate: SliverChildListDelegate(
                         this.isThinkLoading?[
                           Container(
                             height: 300,
                             child: Loading(),
                           )
                         ]: (thinkData.length ==0?[
                        Container(
                        height: 300,
                        child: Empty(
                          isShow: true, child: Container(),
                        ),
                      )
                          ]:[
                          SizedBox(
                          height: Screen.setHeight(15),
                    ),
                    Split(splitData: 'think'),
                    SizedBox(
                      height: Screen.setHeight(15),
                    ),
                    SpannableCountCountPage(thinkDataList: thinkData)
                  ])
                      ),
                    )


                  ]),
                ))
        : Loading();
  }
}
